package com.leo.base.db.router.rule;

import com.leo.base.db.router.function.MurmurHash;
import com.leo.base.db.router.util.PartitionUtil;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.beans.factory.InitializingBean;

/**
 * @ClassName ReadWriteSeparRule
 * @Description
 * @Author wangss
 * @date 2020.09.15 16:55
 * @Version 1.0
 */
public class ReadWriteSeparRule implements InitializingBean {

    private String[] read;
    private String[] write;
    private String shardingField;
    private int[] count;
    private int[] length;

    private PartitionUtil partitionUtil;

    public String getDataSourceKey(String shardingFieldValue, String sqlType) {
        Long hash = MurmurHash.hash(shardingFieldValue);
        int partition = partitionUtil.partition(hash);
        // 查询
        if (SqlCommandType.SELECT.name().equals(sqlType)) {
            return read[partition];
        }
        // 增删改
        return write[partition];
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        partitionUtil = new PartitionUtil(count, length);
    }

    public void setRead(String[] read) {
        this.read = read;
    }

    public void setWrite(String[] write) {
        this.write = write;
    }

    public void setShardingField(String shardingField) {
        this.shardingField = shardingField;
    }

    public void setCount(int[] count) {
        this.count = count;
    }

    public void setLength(int[] length) {
        this.length = length;
    }

    public String getShardingField() {
        return shardingField;
    }
}
